package com.bobo.web.provider.util;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class InsertFile {
    public static void main(String[] args) {


        File f = new File("/Users/allin264/Desktop/123456.html");
        // 读取文件内容
        String fileStr = readfile(f);
//        List<String> resutList = getSrings(fileStr, Pattern.quote("<!-- end: nav -->") + "(.*?)" + Pattern.quote("<!-- start: footer -->"));

        // 写入文件
        writeListToFile(fileStr, f.getPath());
    }

    /**
     * 实现写操作方法
     */
    public static void writeListToFile(String listStr, String fileName) {
        File file = new File(fileName);// 要写入的文件路径
        if (!file.exists()) {// 判断文件是否存在
            try {
                file.createNewFile();// 如果文件不存在创建文件
                System.out.println("文件" + file.getName() + "不存在已为您创建!");
            } catch (IOException e) {
                System.out.println("创建文件异常!");
                e.printStackTrace();
            }
        } else {
            System.out.println("文件" + file.getName() + "- - -已存在!");
        }
        String replace = listStr.replace("<head>", "<head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
        // 获取该文件的缓冲输出流
        BufferedWriter bufferedWriter;
        try {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            // 写入信息
            bufferedWriter.write(replace);
            bufferedWriter.flush();// 清空缓冲区
            bufferedWriter.close();// 关闭输出流
        } catch (Exception e) {
            System.out.println("写入文件异常!");
            e.printStackTrace();
        }
    }


    /**
     * 读取文件内容
     *
     * @return
     * @throws IOException
     */
    @SuppressWarnings("resource")
    public static String readfile(File file) {
        StringBuffer strBuf = new StringBuffer();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            int tempchar;
            while ((tempchar = bufferedReader.read()) != -1) {
                strBuf.append((char) tempchar);
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strBuf.toString();
    }


    /**
     * 获取html中指定内容
     *
     * @param input 文件所有内容
     * @param regex 正则表达式
     * @return
     */
    public static List<String> getSrings(String input, String regex) {
        List<String> result = new LinkedList<String>();
        Pattern pat = Pattern.compile(regex, Pattern.DOTALL);
        Matcher mat = pat.matcher(input);
        while (mat.find()) {
            result.add(mat.group(1));
        }
        return result;
    }


}
